package com.javastudy.forum.service.impl;

import com.javastudy.forum.common.AppResult;
import com.javastudy.forum.common.ResultCode;
import com.javastudy.forum.dao.UserMapper;
import com.javastudy.forum.exception.ApplicationException;
import com.javastudy.forum.model.User;
import com.javastudy.forum.service.IUserService;
import com.javastudy.forum.utils.MD5Utils;
import com.javastudy.forum.utils.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.javastudy.forum.utils.StringUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author Chooker
 * @create 2023-08-16 16:59
 */
@Slf4j //日志
@Service
public class UserServiceImpl implements IUserService {
    @Resource
    UserMapper userMapper;

    @Override
    public User selectByUsername(String username) {
        //非空校验
        if (StringUtils.isEmpty(username)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }
        //根据用户名查询用户信息
        User user = userMapper.selectByUsername(username);

        return user;
    }

    @Override
    public int createNormalUser(User user) {
        //非空校验
        if (user == null || StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getNickname()) ||
                StringUtils.isEmpty(user.getPassword()) || StringUtils.isEmpty(user.getSalt())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验用户名是否存在
        User exitsUser = userMapper.selectByUsername(user.getUsername());
        if (exitsUser != null) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));

        }
        //为性別设置默认值
        if (user.getGender() != null) {
            if (user.getGender() < 0 || user.getGender() > 2) {
                user.setGender((byte) 2);
            }
        } else {
            user.setGender((byte) 2);

        }
        //为发帖数设置默认值
        user.setArticlecount(0);
        //设置是否管理员
        user.setIsadmin((byte) 0);

        //设置状态
        user.setState((byte) 0);

        //设置是否删除
        user.setDeletestate((byte) 0);

        //设置时间
        Date date = new Date();
        user.setCreatetime(date);
        user.setUpdatetime(date);

        //写入数据库
        int row = userMapper.insertSelective(user);

        if (row != 1) {
            //打印日志
            log.warn(ResultCode.FAILED_CREATE.toString() + "  注册用户失败,username:" + user.getUsername());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE));
        }

        return row;
    }

    @Override
    public User login(String username, String password) {
        //非空校验
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }
        User user = selectByUsername(username);
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常 ---防止恶意猜测
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        //密码校验
        boolean flag = MD5Utils.verifyOriginalAndCiphertext(password, user.getSalt(), user.getPassword());
        if (!flag) {
            //打印日志
            log.warn("密码输入错误: username: " + username + "  password: " + password);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));

        }
        return user;
    }

    @Override
    public User selectById(Long id) {
        if (id < 0 || id == null) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }

    @Override
    public void addOneArticleCountById(Long id) {
        if (id < 0 || id == null) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询现有的用户信息
        User user = selectById(id);
        // 校验用户是否为空
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        user.setArticlecount(user.getArticlecount() + 1);
        user.setUpdatetime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(user);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }

    @Override
    public void subOneArticleCountById(Long id) {
        if (id < 0 || id == null) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 查询现有的用户信息
        User user = selectById(id);
        // 校验用户是否为空
        if (user == null) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        user.setArticlecount(user.getArticlecount() - 1);
        // 判断减1之后，用户的发帖数是否小于0
        if (user.getArticlecount() < 0) {
            // 如果小于0，则设置为0
            user.setArticlecount(0);
        }
        user.setUpdatetime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(user);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyInfo(User user) {
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 定义一个标识
        boolean checkParam = false;
        //更新用户
        User updateUser = new User();
        updateUser.setId(user.getId());
        //用户名
        if (!StringUtils.isEmpty(user.getUsername())) {
            User user1 = selectByUsername(user.getUsername());
            if (user1 == null) {
                updateUser.setUsername(user.getUsername());
                checkParam = true;
            } else {
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
            }

        }
        //昵称
        if (!StringUtils.isEmpty(user.getNickname())) {
            updateUser.setNickname(user.getNickname());
            checkParam = true;
        }
        //性别
        if (user.getGender() != null) {
            // 设置性别
            updateUser.setGender(user.getGender());
            // 校验有效性 0女 1男 2保密
            if (updateUser.getGender() < 0 || updateUser.getGender() > 2) {
                // 处理方式1：设置成默认值
                // 处理方式2：设置为null, 表示保持原来的性别，不更新数据库
                updateUser.setGender((byte) 2);
            }
            // 更新标识
            checkParam = true;

        }
        //电话号码
        if (!StringUtils.isEmpty(user.getPhonenum())) {
            updateUser.setPhonenum(user.getPhonenum());
            checkParam = true;
        }
        //邮箱
        if (!StringUtils.isEmpty(user.getEmail())) {
            updateUser.setEmail(user.getEmail());
            checkParam = true;
        }
        //简介
        if (!StringUtils.isEmpty(user.getRemark())) {
            updateUser.setRemark(user.getRemark());
            checkParam = true;
        }

        if (checkParam == false) {
            throw new ApplicationException("所有信息不能同时为空");
        }
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
    }

    @Override
    public void modifyPassword(Long id, String newPassword, String oldPassword) {
        if (id < 0 || id == null || StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(oldPassword)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        User user = selectById(id);
        if (user == null || user.getDeletestate() == 1) {
            // 打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + " user id = " + id);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        if (!MD5Utils.verifyOriginalAndCiphertext(oldPassword, user.getSalt(), user.getPassword())) {
            // 打印日志
            log.warn(ResultCode.FAILED_PASSWORD_CHECK.toString() + " user id = " + id + ", old password = " + oldPassword);
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PASSWORD_CHECK));
        }
        String salt = UUIDUtils.UUID_32();
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setSalt(salt);
        updateUser.setPassword(MD5Utils.md5Salt(newPassword, salt));
        updateUser.setUpdatetime(new Date());
        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        if (row != 1) {
            // 打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }
}
